package com.lqq.msmservice.controller;

import com.lqq.commonutils.R;
import com.lqq.msmservice.service.MsmService;
import com.lqq.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController//返回json数据
@RequestMapping("/edumsm/msm")//请求的url
//@CrossOrigin//解决跨越
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送短信方法
    @GetMapping("/send/{phone}")
    public R sendMsm(@PathVariable("phone") String phone) {

        //查缓存，看是否存在验证码，不存在就生成
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok().message("短信已经存在了");
        }

        //缓存无验证码，生成随机值，向阿里云传递
        code = RandomUtil.getSixBitRandom();
        String[] param = new String[10];
        param[0] = code;

        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);
        if (isSend) {
            //发送成功，写缓存，过期时间为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok().message("短信发送成功");
        }
        else {
            return R.error().message("短信发送失败");
        }
    }
}
